package com.shoothzj.example.storage.hibernate;

import com.shoothzj.example.storage.api.IRepo;
import org.hibernate.SessionFactory;

import javax.persistence.Entity;
import java.io.Serializable;
import java.util.List;

public class HibernateGenericService<T> extends HibernateService implements IRepo<T> {
    private final Class<T> t;

    private final String className;

    public HibernateGenericService(Class<T> tClass, SessionFactory sessionFactory) {
        super(sessionFactory);
        this.t = tClass;
        this.className = tClass.getName();
        Entity entity = tClass.getAnnotation(Entity.class);
        if (entity == null) {
            throw new IllegalArgumentException("class must be annotated with @Entity");
        }
    }

    public Serializable insert(T t) {
        return this.save(t);
    }

    public long deleteById(Serializable id) {
        return this.update("DELETE FROM " + className + " WHERE id=" + id);
    }

    public long deleteAll() {
        return this.update("DELETE FROM " + className);
    }

    public T findById(Serializable id) {
        return this.get(id, t);
    }

    @Override
    public List<T> findAll() {
        return this.query("FROM " + className, t);
    }

    @Override
    public long count() {
        Object object = this.queryUniqueResult("SELECT COUNT(*) FROM " + className);
        if (object == null) {
            throw new IllegalStateException("this table does not exist");
        }
        return (long) object;
    }
}
